package com.aaron.guide.nettystudy.handler;

import com.aaron.guide.nettystudy.entity.RpcRequest;
import com.aaron.guide.nettystudy.entity.RpcResponse;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName NettyServerHandler
 * @description:
 * @author: 荣燊
 * @create: 2021-05-14 22:24
 **/

/**
 * 这一步就是KyroDecode入栈处理之后（解码了，字节转化为对象了），传输给下一个ChannelInboundHandler处理的数据。
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
    private static final AtomicInteger atomicInteger = new AtomicInteger(1);//原子类

    //入栈，读取Socket/Transport数据之后再发送其他的数据出去
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            RpcRequest rpcRequest = (RpcRequest) msg;
            logger.info("server receive msg: [{}] ,times:[{}]", rpcRequest, atomicInteger.getAndIncrement());

            //给RpcResponse实体类赋值
            RpcResponse messageFromServer = RpcResponse.builder().message("message from server").build();

            //ChannelFuture的作用,写入的是RpcResponse对象。writeAndFlush()方法调用了出栈方法吗？
            ChannelFuture f = ctx.writeAndFlush(messageFromServer);
            // future-listener机制
            f.addListener(ChannelFutureListener.CLOSE);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("server catch exception",cause);
        ctx.close();
    }
}
